#include "tlistview.h"
#include <QMouseEvent>
#include <QScrollBar>
#include <QTimer>

TListView::TListView(QWidget *parent) :
    QListView(parent)
{
    mBar = this->verticalScrollBar();
    pressTime = 500;
    mIsDoubleClick = false;
    isDown = false;
    mTimer = new QTimer(this);
    mTimer->setSingleShot(true);
    connect(mTimer,SIGNAL(timeout()),this,SLOT(timeOutProcess()));
}

bool TListView::isOnBottom()
{
    if (mBar->value() >= mBar->maximum()) {
        return true;
    }
    else {
        return false;
    }
}

bool TListView::isOnTop()
{
    if (mBar->value()<=mBar->minimum()) {
        return true;
    }
    else {
        return false;
    }
}

int TListView::pages()
{
    return ((mBar->maximum()-mBar->minimum())+mBar->pageStep()-1)/(mBar->pageStep())+1;
}

int TListView::currentPage()
{
    return ((mBar->value()-mBar->minimum())+mBar->pageStep()-1)/(mBar->pageStep())+1;
}

void TListView::setBarRange(int min, int max)
{
    Q_UNUSED(min);
    Q_UNUSED(max);
}

void TListView::showEvent(QShowEvent *e)
{
    QListView::showEvent(e);
    mBar->setRange(0,(pages()-1)*mBar->pageStep());
}

QModelIndexList TListView::selectedIndexes() const
{
    return QListView::selectedIndexes();
}

void TListView::pageUp()
{
    mBar->setValue(mBar->value()-mBar->pageStep());
}

void TListView::pageDown()
{
    mBar->setValue(mBar->value()+mBar->pageStep());
}

void TListView::timeOutProcess()
{
    if (isDown) {
        emit longPress(this->currentIndex());
    }
    else if (!mIsDoubleClick) {
        emit singleclicked(this->currentIndex());
    }
}

void TListView::mousePressEvent(QMouseEvent *event)
{
    isDown = true;
    if (mTimer->isActive()) {
        mIsDoubleClick = true;
        emit doubleClicked(this->currentIndex());
        mTimer->stop();
        return;
    }
    else {
        mTimer->start(1000);
        mIsDoubleClick = false;
    }
    QListView::mousePressEvent(event);

}

void TListView::mouseReleaseEvent(QMouseEvent *event)
{
    isDown = false;
    if (mTimer->isActive()) {
        mTimer->stop();
        mTimer->start(250);
    }
    QListView::mouseReleaseEvent(event);
}
